package me.numark.fragments;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.google.gson.Gson;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import me.numark.R;
import me.numark.model.UserListResponse;
import me.numark.net.BaseResponse;
import me.numark.net.NetworkConstants;
import me.numark.net.RequestServerTask;
import me.numark.utils.Constants;
import me.numark.utils.Global;
import me.numark.utils.HttpUtil;
import me.numark.utils.Utils;
import me.numark.view.UsersListAdapter;

/**
 * Created by ytian on 15/8/1.
 */
public class FriendsFragment extends BaseListFragment {

    private static final String ARG_FROM_SETTING = "fromSetting";

    public static final String ARG_USERID = "userid";

    private static final String ARG_TYPE = "type";

    public static final int TYPE_FIND_SITE = 1;
    public static final int TYPE_FIND_CONTACTS = 6;
    public static final int TYPE_FIND_WEIBO = 7;
    public static final int TYPE_FOLLOW = 2;
    public static final int TYPE_BOTH = 3;
    public static final int TYPE_FAN = 4;
    public static final int TYPE_SEARCH = 5;

    private int friendsType;

    private int mUserId;

    private String weiboId, weiboToken;

    public UsersListAdapter mUsersListAdapter;

    private String contacts;

    private boolean hasUploadedContacts;

    boolean fromSetting;

    public int type;

    protected boolean isVisible;

    public static FriendsFragment newInstance(int userId, boolean fromSetting, int type) {
        FriendsFragment fragment = new FriendsFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_USERID, userId);
        args.putBoolean(ARG_FROM_SETTING, fromSetting);
        args.putInt(ARG_TYPE, type);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mUserId = getArguments().getInt(ARG_USERID);
        fromSetting = getArguments().getBoolean(ARG_FROM_SETTING, false);
        type = getArguments().getInt(ARG_TYPE);
        dataList = new ArrayList();
        if (type == TYPE_FIND_SITE) {
            mUsersListAdapter = new UsersListAdapter(dataList, this, mUserId, UsersListAdapter.TYPE_FROM_REGESITER);
        }else {
            mUsersListAdapter  = new UsersListAdapter(dataList,this,mUserId,UsersListAdapter.TYPE_NORMAL);
        }
        mAdapter = mUsersListAdapter;
    }

    public void loadWithContacts() {
        contacts = Utils.buildContacts(getActivity()).toString();
        loadData(0);
    }

    public void loadWithWeibo(String weiboId, String weiboToken) {
        this.weiboId = weiboId;
        this.weiboToken = weiboToken;
        loadData(0);
    }

    @Override
    public void initUI(View view) {
        super.initUI(view);
        toolbar.setVisibility(View.GONE);
    }

    public Set<Integer> mCheckedUsers = new HashSet<>();

    @Override
    public void loadMore(int itemsCount, int maxLastVisiblePosition) {
        super.loadMore(itemsCount, maxLastVisiblePosition);
        loadData(itemsCount);
    }

    @Override
    public void refresh() {
        super.refresh();
    }

    @Override
    public void onRefresh() {
        super.onRefresh();
            loadData(0);
    }

    @Override
    public void showEmptyView() {
        super.showEmptyView();
    }

    @Override
    protected BaseResponse parseData(String data) {
        Gson gson = Global.getGson();
        return gson.fromJson(data, UserListResponse.class);
    }


    private void loadData(final int start) {
        new RequestServerTask<UserListResponse>(UserListResponse.class) {
            @Override
            protected String requestServer() {
                switch (type) {
                    default:
                    case TYPE_FIND_SITE:
                        Map<String, Object> params = new HashMap<>();
                        params.put("start", String.valueOf(start));
                        params.put("limit", String.valueOf(Constants.PAGE_SIZE));
                        params.put("uid", String.valueOf(mUserId));
                        if (fromSetting)
                            params.put("nosite", "1");
                        if (start > 0 && lastResponseTime > 0) {
                            params.put("time", String.valueOf(lastResponseTime));
                        }
                        /*if (shouldUploadContacts()) {
                            JSONObject object = buildContactsObject();
                            if (object != null) {
                                params.put("contacts", object);
                            }
                        }*/
                        return HttpUtil.post(String.format(NetworkConstants.REGISTRATION_FRIENDS_URL, mUserId), params);

                    case TYPE_FIND_CONTACTS:
                        Map<String, Object> params2 = new HashMap<>();
                        params2.put("start", String.valueOf(start));
                        params2.put("limit", String.valueOf(Constants.PAGE_SIZE));
                        params2.put("uid", String.valueOf(mUserId));
                        if (fromSetting)
                            params2.put("nosite", "1");
                        if (start > 0 && lastResponseTime > 0) {
                            params2.put("time", String.valueOf(lastResponseTime));
                        }
                        if (shouldUploadContacts()) {
                            JSONObject object = buildContactsObject();
                            if (object != null) {
                                params2.put("contacts", object);
                            }
                        }
                        return HttpUtil.post(String.format(NetworkConstants.REGISTRATION_FRIENDS_URL, mUserId), params2);
                    case TYPE_FIND_WEIBO:
                        Map<String, Object> params3 = new HashMap<>();
                        params3.put("start", String.valueOf(start));
                        params3.put("limit", String.valueOf(Constants.PAGE_SIZE));
                        params3.put("uid", String.valueOf(mUserId));
                        if (fromSetting)
                            params3.put("nosite", "1");
                        if (start > 0 && lastResponseTime > 0) {
                            params3.put("time", String.valueOf(lastResponseTime));
                        }
                        if (shouldUploadContacts()) {
                            JSONObject object = buildContactsObject();
                            if (object != null) {
                                params3.put("contacts", object);
                            }
                        }
                        return HttpUtil.post(String.format(NetworkConstants.REGISTRATION_FRIENDS_URL, mUserId), params3);
                    case TYPE_FOLLOW:
                        Map<String, Object> params4 = new HashMap<>();
                        params4.put("start", String.valueOf(start));
                        params4.put("limit", String.valueOf(Constants.PAGE_SIZE));
                        params4.put("uid", String.valueOf(mUserId));

                        if (start > 0 && lastResponseTime > 0) {
                            params4.put("time", String.valueOf(lastResponseTime));
                        }
                        return HttpUtil.get(String.format(NetworkConstants.FOLLOWS_URL, mUserId), params4);
                    case TYPE_BOTH:
                        Map<String, Object> params5 = new HashMap<>();
                        params5.put("start", String.valueOf(start));
                        params5.put("limit", String.valueOf(Constants.PAGE_SIZE));
                        params5.put("uid", String.valueOf(mUserId));

                        if (start > 0 && lastResponseTime > 0) {
                            params5.put("time", String.valueOf(lastResponseTime));
                        }
                        return HttpUtil.get(String.format(NetworkConstants.MUTUAL_CONCERN_URL, mUserId), params5);
                    case TYPE_FAN:
                        Map<String, Object> params6 = new HashMap<>();
                        params6.put("start", String.valueOf(start));
                        params6.put("limit", String.valueOf(Constants.PAGE_SIZE));
                        params6.put("uid", String.valueOf(mUserId));

                        if (start > 0 && lastResponseTime > 0) {
                            params6.put("time", String.valueOf(lastResponseTime));
                        }
                        return HttpUtil.get(String.format(NetworkConstants.FANS_URL, mUserId), params6);
                    case TYPE_SEARCH: {
                        Map<String, Object> params1 = new HashMap<>();
                        params1.put("start", String.valueOf(start));
                        params1.put("limit", String.valueOf(Constants.PAGE_SIZE));
                        params1.put("text", searchKey);
                        params1.put("type", "account");
                        return HttpUtil.get(String.format(NetworkConstants.SEARCH_URL, Global.getCurrentUid()), params1);
                    }
                }
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                endRefreshing();
            }

            @Override
            protected void onSuccess(UserListResponse result) {
                bindData(result, start == 0);
            }
        }.start();
    }

    private JSONObject buildContactsObject() {
        try {
            JSONObject object = new JSONObject();
            if (!hasUploadedContacts && !TextUtils.isEmpty(contacts)) {
                object.put("cellphone", contacts);
            }
            if (isWeiboDataValid()) {
                JSONObject weiboObject = new JSONObject();
                weiboObject.put("uid", weiboId);
                weiboObject.put("token", weiboToken);
                object.put("weibo", weiboObject);
            }
            return object;
        } catch (Exception ignored) {

        }
        return null;
    }

    private boolean isWeiboDataValid() {
        return !TextUtils.isEmpty(weiboId) && !TextUtils.isEmpty(weiboToken);
    }

    private boolean shouldUploadContacts() {
        if (!hasUploadedContacts && !TextUtils.isEmpty(contacts)) {
            return true;
        }
        if (isWeiboDataValid()) {
            return true;
        }
        return false;
    }
    int i = 0;
    @Override
    protected void addDataToList(BaseResponse response, boolean isNew) {
        UserListResponse resp = (UserListResponse) response;
        if (isNew) {
            mUsersListAdapter.clear();
        }
        if (i==1) {
            mUsersListAdapter.append(resp.data);
        }else {
            mUsersListAdapter.append(resp.data);
        }
        setHasMore(resp.has_more);
        i++;
    }

    public void addFriends() {

        if (mCheckedUsers.isEmpty()) {
            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
            return;
        }
        new RequestServerTask<BaseResponse>(BaseResponse.class) {
            @Override
            protected String requestServer() {
                Map<String, Object> params = new HashMap<>();

                params.put("uid", String.valueOf(mUserId));
                params.put("f_uids", TextUtils.join("|", mCheckedUsers));
                return HttpUtil.post(String.format(NetworkConstants.REGISTER_FOLLOWS_URL, mUserId), params);

            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                endRefreshing();
            }

            @Override
            protected void onSuccess(BaseResponse result) {
                getActivity().setResult(Activity.RESULT_OK);
                getActivity().finish();
                Utils.showToast(R.string.add_friends_success);
            }
        }.start();
    }
}
